<template>
  <div class="sales-invoice-add">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>新增发票</span>
          <div class="header-actions">
            <el-button type="primary" :loading="submitting" @click="onSubmit">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button text type="info" @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" status-icon>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="发票号码" prop="invoiceNo">
              <el-input v-model="form.invoiceNo" placeholder="请输入发票号码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单ID" prop="orderId">
              <el-select v-model="form.orderId" placeholder="请选择订单" filterable clearable @change="onOrderChange"
                :loading="ordersLoading" style="width: 100%">
                <el-option v-for="opt in orderOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable clearable :loading="customersLoading"
                :no-data-text="'暂无客户数据'" style="width: 100%">
                <el-option v-for="opt in customerOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票日期" prop="invoiceDate">
              <el-date-picker v-model="form.invoiceDate" type="date" placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="form.invoiceType" placeholder="请选择类型" style="width: 100%">
                <el-option label="普通" value="普通" />
                <el-option label="专用" value="专用" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="invoiceStatus">
              <el-select v-model="form.invoiceStatus" placeholder="请选择状态" style="width: 100%">
                <el-option v-for="opt in invoiceStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-input-number v-model="form.taxRate" :min="0" :max="100" :step="1" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="备注(可选)" clearable type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider>发票明细</el-divider>

      <div class="table-actions">
        <el-button type="primary" plain @click="addItem">新增一行</el-button>
      </div>
      <el-table :data="form.invoiceDetails" border size="small" style="width: 100%">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column label="产品名称" min-width="180">
          <template #default="{ row }">
            <el-input v-model="row.productName" placeholder="产品名称" clearable />
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="140">
          <template #default="{ row }">
            <el-input v-model="row.specification" placeholder="规格" clearable />
          </template>
        </el-table-column>
        <el-table-column label="单位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.unit" placeholder="单位" clearable />
          </template>
        </el-table-column>
        <el-table-column label="数量" width="130" align="right">
          <template #default="{ row }">
            <el-input-number v-model="row.quantity" :min="1" :step="1" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="单价(不含税)" width="160" align="right">
          <template #default="{ row }">
            <el-input-number v-model="row.unitPrice" :min="0" :step="0.01" :precision="2" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="税率(%)" width="130" align="right">
          <template #default="{ row }">
            <el-input-number v-model="row.taxRate" :min="0" :max="100" :step="1" />
          </template>
        </el-table-column>
        <el-table-column label="税额" width="140" align="right">
          <template #default="{ row }">{{ formatMoney(row.taxAmount) }}</template>
        </el-table-column>
        <el-table-column label="小计(含税)" width="160" align="right">
          <template #default="{ row }">{{ formatMoney(row.subtotalAmount) }}</template>
        </el-table-column>
        <el-table-column label="行备注" min-width="160">
          <template #default="{ row }">
            <el-input v-model="row.remarks" placeholder="备注" clearable />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ $index }">
            <el-button type="danger" text @click="removeItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary">
        <div class="summary-item">
          <span>合计(不含税)：</span>
          <b>{{ formatMoney(subtotalAmount) }}</b>
        </div>
        <div class="summary-item">
          <span>税额：</span>
          <b>{{ formatMoney(taxAmount) }}</b>
        </div>
        <div class="summary-item">
          <span>发票金额(含税)：</span>
          <b class="total">{{ formatMoney(invoiceAmount) }}</b>
        </div>
      </div>
    </el-card>
  </div>

</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { APIs } from '@/Http/http'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'

type InvoiceDetail = {
  productName: string
  specification: string
  unit: string
  quantity: number
  unitPrice: number
  amount: number
  taxRate: number
  taxAmount: number
  subtotalAmount: number
  remarks: string
}

type SalesInvoiceForm = {
  invoiceNo: string
  orderId: number | null
  customerId: number | null
  invoiceAmount: number
  invoiceDate: string | Date
  invoiceType: string
  invoiceStatus: number
  taxRate: number
  taxAmount: number
  subtotalAmount: number
  remarks: string
  createName: string
  invoiceDetails: InvoiceDetail[]
}

const router = useRouter()
const submitting = ref(false)
const formRef = ref<FormInstance>()
const store = useCounterStore()
const ordersLoading = ref(false)
const orderOptions = ref<Array<{ label: string, value: number, customerId?: number }>>([])
const customersLoading = ref(false)
const customerOptions = ref<Array<{ label: string, value: number }>>([])
const invoiceStatusOptions = ref([
  { label: '待开具', value: 0 },
  { label: '已开具', value: 1 },
  { label: '已作废', value: 2 },
  { label: '已红冲', value: 3 },
])

const form = reactive<SalesInvoiceForm>({
  invoiceNo: '',
  orderId: null,
  customerId: null,
  invoiceAmount: 0,
  invoiceDate: '',
  invoiceType: '',
  invoiceStatus: 0,
  taxRate: 13,
  taxAmount: 0,
  subtotalAmount: 0,
  remarks: '',
  createName: store.Users.userNickname || '',
  invoiceDetails: [
    { productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: 13, taxAmount: 0, subtotalAmount: 0, remarks: '' }
  ]
})

const rules = reactive<FormRules<SalesInvoiceForm>>({
  invoiceNo: [
    { required: true, message: '请输入发票号码', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请输入客户ID', trigger: 'blur' }
  ],
  invoiceDate: [
    { required: true, message: '请选择发票日期', trigger: 'change' }
  ]
})

const subtotalAmount = computed(() => {
  return form.invoiceDetails.reduce((sum, it) => sum + (Number(it.quantity) * Number(it.unitPrice) || 0), 0)
})
const taxAmount = computed(() => {
  return Number((form.invoiceDetails.reduce((sum, it) => sum + (Number(it.quantity) * Number(it.unitPrice) * (Number(it.taxRate) / 100) || 0), 0)).toFixed(2))
})
const invoiceAmount = computed(() => Number((subtotalAmount.value + taxAmount.value).toFixed(2)))

watch(
  () => form.invoiceDetails.map(i => [i.quantity, i.unitPrice, i.taxRate]),
  () => {
    form.invoiceDetails.forEach(i => {
      i.amount = Number((Number(i.quantity) * Number(i.unitPrice)).toFixed(2))
      i.taxAmount = Number((Number(i.quantity) * Number(i.unitPrice) * (Number(i.taxRate) / 100)).toFixed(2))
      i.subtotalAmount = Number((i.amount + i.taxAmount).toFixed(2))
    })
    form.subtotalAmount = Number(subtotalAmount.value.toFixed(2))
    form.taxAmount = Number(taxAmount.value.toFixed(2))
    form.invoiceAmount = Number(invoiceAmount.value.toFixed(2))
  },
  { deep: true }
)

function addItem() {
  form.invoiceDetails.push({ productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: form.taxRate, taxAmount: 0, subtotalAmount: 0, remarks: '' })
}

function removeItem(index: number) {
  form.invoiceDetails.splice(index, 1)
}

function formatMoney(v: number | string) {
  const n = Number(v || 0)
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function onReset() {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', { type: 'warning' }).then(() => {
    form.invoiceNo = ''
    form.orderId = null
    form.customerId = null
    form.invoiceDate = ''
    form.taxRate = 13
    form.invoiceType = ''
    form.invoiceStatus = 0
    form.remarks = ''
    form.createName = store.Users.userNickname || ''
    form.invoiceDetails = [{ productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: 13, taxAmount: 0, subtotalAmount: 0, remarks: '' }]
  }).catch(() => { })
}

function goBack() {
  router.back()
}

async function onSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!customerOptions.value.length) {
      ElMessage.error('暂无客户可选，无法提交')
      return
    }
    if (!form.customerId) {
      ElMessage.error('请选择客户')
      return
    }
    try {
      submitting.value = true
      // 组织与后端一致的数据结构
      const payload = {
        invoiceNo: form.invoiceNo,
        orderId: Number(form.orderId) || 0,
        customerId: Number(form.customerId) || 0,
        invoiceAmount: Number(invoiceAmount.value) || 0,
        invoiceDate: form.invoiceDate ? new Date(form.invoiceDate).toISOString() : new Date().toISOString(),
        invoiceType: form.invoiceType || '普通',
        invoiceStatus: Number(form.invoiceStatus) || 0,
        taxRate: Number(form.taxRate) || 0,
        taxAmount: Number(taxAmount.value) || 0,
        subtotalAmount: Number(subtotalAmount.value) || 0,
        remarks: form.remarks || '',
        createName: store.Users.userNickname || form.createName || '',
        invoiceDetails: form.invoiceDetails.map(i => ({
          productName: i.productName,
          specification: i.specification,
          unit: i.unit,
          quantity: Number(i.quantity) || 0,
          unitPrice: Number(i.unitPrice) || 0,
          amount: Number(i.amount) || 0,
          taxRate: Number(i.taxRate) || 0,
          taxAmount: Number(i.taxAmount) || 0,
          subtotalAmount: Number(i.subtotalAmount) || 0,
          remarks: i.remarks || ''
        }))
      }
      const res = await APIs.post('/api/SalesInvoice/AddSalesInvoice', payload)
      if (res && (res.status === 200 || res.status === 201)) {
        ElMessage.success('新增成功')
        // 新增成功后跳转到发票列表页面
        setTimeout(() => {
          router.push('/SalesInvoice')
        }, 500)
      } else {
        ElMessage.error('保存失败')
      }
    } catch (error: any) {
      ElMessage.error(error?.response?.data?.message || '请求失败')
    } finally {
      submitting.value = false
    }
  })
}

function onOrderChange(val: number) {
  const found = orderOptions.value.find(o => o.value === val)
  if (found && found.customerId != null) {
    form.customerId = Number(found.customerId)
  }
}

async function loadOrderOptions() {
  try {
    ordersLoading.value = true
    const res = await APIs.get('/api/SalesInvoice/DingdanQuery')
    const list = Array.isArray(res?.data) ? res.data : (res?.data?.data || [])
    orderOptions.value = list.map((it: any) => ({
      value: Number(it.orderId ?? it.id ?? it.OrderId ?? 0),
      label: String(it.dingDanBianHao ?? it.orderNo ?? it.orderCode ?? it.name ?? it.OrderNo ?? it.id ?? ''),
      customerId: Number(it.customerId ?? it.CustomerId ?? 0)
    })).filter((x: any) => x.value)
  } catch (e) {
    ElMessage.error('订单列表加载失败')
  } finally {
    ordersLoading.value = false
  }
}

onMounted(() => {
  loadOrderOptions()
  loadCustomerOptions()
})

async function loadCustomerOptions() {
  try {
    customersLoading.value = true
    const res = await APIs.get('/api/SalesInvoice/clietQuery')
    const list = Array.isArray(res?.data) ? res.data : (res?.data?.data || [])
    customerOptions.value = list.map((it: any) => ({
      value: Number(it.customerID ?? it.customerId ?? it.CustomerId ?? it.id ?? 0),
      label: String(it.customername ?? it.customerName ?? it.name ?? '')
    })).filter((x: any) => x.value)
    if (!customerOptions.value.length) {
      ElMessage.warning('暂无客户数据，请先在基础资料中新增客户')
    }
  } catch (e) {
    ElMessage.error('客户列表加载失败')
  } finally {
    customersLoading.value = false
  }
}
</script>

<style scoped>
.sales-invoice-add {
  padding: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.table-actions {
  margin-bottom: 8px;
}

.summary {
  margin-top: 12px;
  display: flex;
  gap: 24px;
  justify-content: flex-end;
}

.summary-item span {
  color: var(--el-text-color-regular);
  margin-right: 8px;
}

.summary-item .total {
  color: var(--el-color-primary);
}
</style>
